import 'dart:collection';

import 'package:cloud_phone_manager/provider/AdbCurrentChangeProvider.dart';
import 'package:cloud_phone_manager/provider/AdbDevicesProvider.dart';
import 'package:cloud_phone_manager/utils/CmdUtils.dart';
import 'package:cloud_phone_manager/utils/ConnectUtils.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

/// 设备列表
class DevicesListView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _MyListView();
}

class _MyListView extends State<DevicesListView> {
  final List<AdbDeviceInfo> _list = [];
  HashMap<String, AdbDeviceInfo> _map = HashMap();
  AdbDevicesProvider? provider;
  bool _isInit = false;
  bool _mounted = false;
  AdbCurrentChangeProvider? changeProvider;

  @override
  void initState() {
    super.initState();
    _mounted = true;
    if (!_isInit) {
      _isInit = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    changeProvider ??= Provider.of<AdbCurrentChangeProvider>(context);
    if (provider == null) {
      provider = Provider.of<AdbDevicesProvider>(context);
      provider?.addListener(() {
        List<AdbDeviceInfo> list = provider?.getAdbDevicesInfoList() ?? [];
        bool isHasDefault = false;
        for (AdbDeviceInfo item in list) {
          if (item.name ==
              (ConnectUtils.getInstance().getCurrentChooseDevices()?.name ??
                  "")) {
            isHasDefault = true;
          }
        }
        if (!isHasDefault) {
          AdbDeviceInfo? current = ConnectUtils.getInstance().getCurrentChooseDevices();
          int index = 0;
          for(AdbDeviceInfo item in _list){
            if(item.name == (current?.name??"") ){
              break;
            }
            index++;
          }
          setState(() {
            if(!_mounted){
              return;
            }
            try{
              if(index<_list.length-1){
                _list.removeAt(index);
              }
            }catch(e){}
          });
          ConnectUtils.getInstance().setCurrentDevices(null);
        }
        for (AdbDeviceInfo item in list) {
          if (_map[item.name] == null) {
            _map[item.name] = item;
            setState(() {
              if(!_mounted){
                return;
              }
              _list.add(item);
            });
            if (ConnectUtils.getInstance().getCurrentChooseDevices() == null &&
                item.status) {
              ConnectUtils.getInstance().setCurrentDevices(item);
              changeProvider?.updateCurrentData(ConnectUtils.getInstance().getCurrentChooseDevices());
            }
          } else {
            if (ConnectUtils.getInstance().getCurrentChooseDevices() == null &&
                item.status) {
              ConnectUtils.getInstance().setCurrentDevices(item);
              changeProvider?.updateCurrentData(ConnectUtils.getInstance().getCurrentChooseDevices());
            }
            int index = _list.indexOf(_map[item.name]!);
            setState(() {
              if(!_mounted){
                return;
              }
              _list[index].status = item.status;
            });
          }
        }
      });
    }

    return ListView.builder(
      itemCount: _list.length,
      itemBuilder: (context, index) {
        var phone = ConnectUtils().getCurrentChooseDevices()?.name ?? "";
        debugPrint("${phone}，${_list[index].name}");
        return SizedBox(
          width: MediaQuery.of(context).size.width,
          child: Column(children: [
            Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: Container(
                    height: 10,
                    width: 10,
                    color: phone == _list[index].name ?  Colors.green:Colors.white70,
                  ),
                ),
                Expanded(
                  flex: 8,
                  child: SizedBox(
                    child: ListTile(
                      leading: Icon(_list[index].getIcon()),
                      title: Text(
                        _list[index].name,
                        style: const TextStyle(fontSize: 12),
                      ),
                      subtitle: Text(_list[index].status ? "在线" : "离线"),
                      onTap: () {
                        // 处理列表项点击事件
                        ConnectUtils.getInstance().setCurrentDevices(_list[index]);
                        changeProvider?.updateCurrentData(_list[index]);
                        setState(() {

                        });
                      },
                      onLongPress: () {},
                    ),
                  ),
                ),
                Expanded(
                  flex: 2,
                  child: TextButton(
                    child: const Text(
                      "断开",
                      style: TextStyle(fontSize: 12,fontWeight: FontWeight.bold),
                    ),
                    onPressed: () => {
                      CmdUtils.disconnectAdb(_list[index].name,
                              (success, error, process, suListener) {}),
                      setState(() {
                        if(!_mounted){
                          return;
                        }
                        _list.removeAt(index);
                        if(index+1 < _list.length-1){
                          ConnectUtils.getInstance().setCurrentDevices(_list[index+1]);
                          changeProvider?.updateCurrentData(_list[index+1]);
                        }
                      })
                    },
                  ),
                )
              ],
            ),
            Container(color: Color.fromARGB(15, 0, 0, 0),height: 1,)
          ],),
        );
      },
    );
  }
}
